﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Data;
using System.ServiceModel;
using HouseKeepingPL.HKService;



namespace HouseKeepingPL
{
    public class CreateUserViewModel : ViewModelBase
    {
        User _user;
        List<UserType> _userTypeList;
        ServicesClient _hksClient;

        public CreateUserViewModel()
        {
            _user = new User();
            _hksClient = new ServicesClient();
            CreateUserCmd = new RelayCommand(() => CreateUserCmdExcecute(), ()=> true);
            GetUserTypesToBindableCollection(_hksClient);
        }

        private void GetUserTypesToBindableCollection(ServicesClient hksClient)
        {
            _userTypeList = hksClient.GetUserTypes().ToList();
            userTypes = new CollectionView(_userTypeList);
            userTypes.MoveCurrentTo(_userTypeList[0]);
            userTypes.CurrentChanged += new EventHandler(userTypes_CurrentChanged);
        }

        public ICommand CreateUserCmd { get; private set; }
        private void CreateUserCmdExcecute()
        {
            try
            {
                if (_hksClient != null)
                {

                    if (_hksClient.GetUser(_user.Username) == null)
                    {
                        _hksClient.InsertUser(_user);
                        MessageBox.Show(string.Format("{0}-{1}-{2}\n Successfully created!", _user.Username, _user.Password, _user.UserType.Type));
                    }
                    else
                    {
                        MessageBox.Show("Username is already taken");
                    }
                }
    
            }
            catch
            {
                MessageBox.Show(string.Format("{0}-{1}-{2}\n failed to create", _user.Username, _user.Password, _user.UserType.Type));
            }
            
        }

        void userTypes_CurrentChanged(object sender, EventArgs e)
        {
            _user.UserType = (UserType)userTypes.CurrentItem;
        }


        public CollectionView userTypes { get; private set; } // property for binding

        public String BindUsername
        {
            get { return _user.Username; }
            set { _user.Username = value; }
        }

        public String BindPassword
        {
            get { return _user.Password; }
            set { _user.Password = value; }
        }
      }
}
